import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { isPhone, isEmail } from "@pureadmin/utils";
import {
  getAlarmConfigListApi,
  createAlarmConfigApi,
  updateAlarmConfigApi,
  delAlarmConfigApi,
  getAlarmConfigShowApi
} from "@/api/alarmConfig";
export function usePage() {
  const form = reactive({
    page: 1,
    perPage: 10,
    code: null,
	name: null,
	type: null
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const typeOption =ref([
  	{
  		id: 1,
  		name: '钉钉'
  	},
  	{
  		id: 2,
  		name: '手机短信'
  	},
  	// {
  	// 	id: 3,
  	// 	name: '其他'
  	// }
  ])
  const getAleatType = (type, text = false) => {
    switch (type) {
      case 1:
        return text ? "钉钉" : "primary";
      case 2:
        return text ? "手机短信" : "primary";
      case 3:
        return text ? "其他" : "primary";
    }
  };
  
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "alarmConfigId",
      width: 80
    },
	{
	  label: "报警名称",
	  prop: "name",
	},
    {
      label: "报警编码",
      prop: "code",
    },
    {
    	label: "报警类型",
    	prop: "type",
		cellRenderer: ({ row }) => (
		  <el-tag size="large" type={getAleatType(row.type)} effect="light">
		    {getAleatType(row.type, true)}
		  </el-tag>
		)
    },
    {
    	label: "时间间隔",
    	prop: "interval",
    },
    {
    	label: "推送角色",
    	prop: "noticeStaffs.rbacRole.name",
		formatter: (row) => {
			let arr = []
			for (let item of row.noticeStaffs) {
				arr.push(item.rbacRole.name)
			}
			return arr.join(',')
		},
		minWidth: 160
    },
    {
    	label: "报警类型描述",
    	prop: "describe",
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
	  width: 160
    }
  ];
  function handleSizeChange(val: number) {
    form.page = 1;
    form.perPage = val;
    onSearch()
  }

  function handleCurrentChange(val: number) {
    form.page = val;
	onSearch()
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await getAlarmConfigListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.perPage*1;
    pagination.currentPage = result.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    form.code = null;
    form.name = null;
    form.type = null;
    formEl.resetFields();
    onSearch();
  };
  const formInline = ref();
  async function openDialog(title = "新增", row?: FormItemProps) {
    if (`${title}` == "新增") {
      formInline.value = {
        title: "新增",
		interval: 60
      };
    } else {
      const res = await getAlarmConfigShowApi({
        alarmConfigId: row?.alarmConfigId
      });
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
	  let roleList = []
	  for (let item of res?.result.noticeStaffs) {
	  	roleList.push(item.rbacRole.id)
	  }
      formInline.value = {
        title: "修改",
        alarmConfigId: row?.alarmConfigId ?? "",
        code: res?.result?.code ?? "",
        describe: res?.result?.describe ?? "",
		interval: res?.result?.interval ?? 60,
		name: res?.result?.name ?? "",
		type: res?.result?.type ?? 1,
		roleList: roleList
      };
    }
	formInline.value.typeOption = typeOption.value
    addDialog({
      title: `${title}报警配置信息`,
      props: {
        formInline: formInline
      },
      width: "44%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了报警配置`, {
            type: "success"
          });
          done();
          onSearch();
        }
        FormRef.validate(valid => {
          if (valid) {
            if (title === "新增") {
              createAlarmConfigApi(curData)
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            } else {
              updateAlarmConfigApi(curData)
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();
  });

  function handleDelete(row) {
    delAlarmConfigApi({ alarmConfigId: row.alarmConfigId }).then((res) => {
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      message(`删除成功`, { type: "success" });
      onSearch();
    });
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
	typeOption
  };
}
